import cv2
import face_recognition
import os

# 从指定目录加载含有人脸的图像，返回加载好的人脸模型和对应的名字（即文件名）
def load_faces_from_dir(dirname):
    faces = []
    names = []
    for filename in os.listdir(dirname):
        if filename.split(".")[-1] in ("jpg", "png", "bmp", "gif", "webp", "jpeg"):
            name = filename.split(".")[0]
            try:
                face_image = face_recognition.load_image_file(os.path.join(dirname, filename))
                face_encodings = face_recognition.face_encodings(face_image)
                if len(face_encodings)==0:
                    print("[Warning] 在文件{}中未检测到人脸".format(filename))
                else:
                    faces.append(face_encodings[0])
                    names.append(name)
            except Exception as ex:
                print("[Error] {}".format(ex))
    return faces, names

# 识别出一张图像中的所有人
def get_names_from_image(img, faces, names, tolerance=0.6):
    result = set()
    for encoding in face_recognition.face_encodings(img):
        recognitions = face_recognition.compare_faces(faces, encoding, tolerance)
        for rec, name in zip(recognitions, names):
            if rec:
                result.add(name)
    return result

